﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Finance.Basedatas
{
    public class BaseDataRepository<TEntity> : EfCoreRepository<FinanceDbContext, TEntity, Guid>, IBaseDataRepository<TEntity>
        where TEntity : BaseDataAggregateRootBase
    {
        public BaseDataRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public virtual async Task<TEntity> CreateAsync(TEntity entity)
        {
            DbContext.Set<TEntity>().Add(entity);

            var success = await DbContext.SaveChangesAsync() > 0;

            if (success)
                return entity;

            return null;
        }

        public virtual async Task<List<TEntity>> FindAsync(PageQuery query)
        {
            var entities = await DbContext.Set<TEntity>().AsNoTracking()
                 .WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.Name.Contains(query.Keyword) || (x.Code!=null && x.Code.Contains(query.Keyword)))
                 .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
                 .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
                 .WhereIf(query.ExclusionId.HasValue, x => x.Id != query.ExclusionId.Value)
                 .OrderBy(x=>x.Code).ThenBy(x=>x.Name)
                 .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                 .ToListAsync();

            return entities;
        }

        public virtual Task<TEntity> FindAsync(Guid id)
        {
            var entity = DbContext.Set<TEntity>().AsNoTracking().FirstAsync(x => x.Id == id);

            return entity;
        }

        public virtual async Task<int> GetCountAsync(PageQuery query)
        {
            var count = await DbContext.Set<TEntity>().AsNoTracking()
                 .WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.Name.Contains(query.Keyword) || (x.Code != null && x.Code.Contains(query.Keyword)))
                 .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
                 .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
                 .WhereIf(query.ExclusionId.HasValue, x => x.Id != query.ExclusionId.Value)
                 .CountAsync();

            return count;
        }
    }
}
